<template>
    <div>
        <!--   面包屑导航   -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <!--  卡片视图  -->
        <el-card>
            <!--     警告区       -->
            <el-alert show-icon title="警告：只能选择三级标题" type="warning" :closable="false" ></el-alert>
            <!--      级联选择框    -->
            <el-row style="margin: 15px 0">
                <el-col>
                    <span>选择分类：</span>
                    <el-cascader
                            expand-trigger="hover"
                            v-model="modelCascader"
                            :options="paramsList"
                            :props="propsCascader"
                            @change="changeCascader" clearable></el-cascader>
                </el-col>
            </el-row>
            <!--      tab页签区域      -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button size="mini" type="primary" :disabled="isDisablle" @click="addDialogParmas = true">添加参数</el-button>
                    <el-table :data="manyTabData" border stripe>
                        <el-table-column type="expand">
                            <template v-slot="slot">
                                <el-tag  v-for="(item,i) in slot.row.attr_vals" :key="i" closable @close="closeElTag(slot.row,i)">{{item}}</el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="slot.row.inputVisible"
                                        v-model="slot.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(slot.row)"
                                        @blur="handleInputConfirm(slot.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(slot.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="editOption(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="delOption(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button size="mini" type="primary" :disabled="isDisablle" @click="addDialogParmas = true">添加属性</el-button>
                    <el-table :data="onlyTabData" border stripe>
                        <el-table-column type="expand">
                            <template v-slot="slot">
                                <el-tag  v-for="(item,i) in slot.row.attr_vals" :key="i" closable @close="closeElTag(slot.row,i)">{{item}}</el-tag>
                                <el-input
                                        class="input-new-tag"
                                        v-if="slot.row.inputVisible"
                                        v-model="slot.row.inputValue"
                                        ref="saveTagInput"
                                        size="small"
                                        @keyup.enter.native="handleInputConfirm(slot.row)"
                                        @blur="handleInputConfirm(slot.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(slot.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template v-slot="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="editOption(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="delOption(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!--  添加参数对话框  -->
        <el-dialog
                :title="'添加'+dialogText"
                :visible.sync="addDialogParmas"
                width="50%" @close="addDialogClose">
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item :label=dialogText prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogParmas = false">取 消</el-button>
                <el-button type="primary" @click="addParmas">确 定</el-button>
            </span>
        </el-dialog>
        <!--   修改的对话框     -->
        <el-dialog
                :title="'修改'+dialogText"
                :visible.sync="editDialogParmas"
                width="50%" @close="editDialogClose">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
                <el-form-item :label=dialogText prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogParmas = false">取 消</el-button>
                <el-button type="primary" @click="editParmas">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "params",
        created() {
            this.getParamsList()
        },
        data(){return{
            //用于保存获取到的级联选择框的数据
            paramsList:[],
            //级联选择器的数据绑定对象
            modelCascader:[],
            //级联选择器的定义规则
            propsCascader:{
                value:'cat_id',
                label:'cat_name',
                children:"children"
            },
            //tab导航绑定的属性
            activeName:"many",
            //动态表格数据源
            manyTabData:[],
            //静态表格数据源
            onlyTabData:[],
            //添加对话框的的显示与隐藏
            addDialogParmas:false,
            //对话框form的数据绑定
            addForm:{
                attr_name:''
            },
            //对话框form的数据校验规则
            addFormRules:{
                attr_name:[{ required: true, message: '请输入活动名称', trigger: 'blur' },]
            },
            editDialogParmas:false,
            //对话框form的数据绑定
            editForm:{
            },
            //对话框form的数据校验规则
            editFormRules:{
                attr_name:[{ required: true, message: '请输入活动名称', trigger: 'blur' },]
            }
        }},
        methods:{
            //获取级联选择框的数据
            async getParamsList(){
                var {data:res}=await this.$http.get('categories')
                if (res.meta.status!==200)return this.$message.error('获取数据失败')
                this.paramsList=res.data
            },
            //监听级联选择框的change事件
            changeCascader(){
                this.getCateParamsList()
            },
            //监听tab标签栏改变
            handleClick(){
                this.getCateParamsList()
            },
            //获取分类参数列表
            async getCateParamsList(){
                let num=this.modelCascader.length
                //选中不是第三类的情况下(把双向数据绑定的数据清空)
                if (num!==3){
                    this.modelCascader=[]
                    this.manyTabData=[]
                    this.onlyTabData=[]
                    return
                }
                var {data:res}=await this.$http.get(`categories/${this.getCateId}/attributes`,{params:{sel:this.activeName}})

                if (res.meta.status!==200)return this.$message.error('获取数据失败')

                res.data.forEach(e=>{
                    e.attr_vals=e.attr_vals?e.attr_vals.split(' '):[]
                    e.inputVisible=false
                    e.inputValue=''
                })
                //为不同的tab分配不同的数据源
                if (this.activeName=='many'){
                    this.manyTabData=res.data
                }else {
                    this.onlyTabData=res.data
                }

            },
            //关闭对话框
            addDialogClose(){
                this.$refs.addFormRef.resetFields()
            },
            //添加动态/静态属性
            async addParmas(){
                this.$refs.addFormRef.validate(async valid=>{
                    if (!valid)return
                    var {data:res}=await this.$http.post(`categories/${this.getCateId}/attributes`,{
                        attr_name:this.addForm.attr_name,
                        attr_sel:this.activeName
                    })
                    if (res.meta.status!==201)return this.$message.error('数据获取错误')
                    this.$message.success('数据添加成功')
                    this.getCateParamsList()
                    this.addDialogParmas=false
                })
            },
            //编辑属性擦偶作
            async editOption(id){
                this.editDialogParmas=true
                var {data:res}=await this.$http.get(`categories/${this.getCateId}/attributes/${id}`,{params:{
                        attr_sel:this.activeName
                    }})
                if (res.meta.status!==200)return this.$message.error('获取数据错误')
                this.editForm=res.data
            },
            //编辑提交数据
            editParmas(){
                this.$refs.editFormRef.validate(async valid=>{
                    if(!valid)return
                    var{data:res}=await this.$http.put(`categories/${this.getCateId}/attributes/${this.editForm.attr_id}`,{
                        attr_name:this.editForm.attr_name,attr_sel:this.activeName
                    })
                    if(res.meta.status!==200)return this.$message.error('获取信息失败')
                    this.$message.success('修改信息成功')
                    this.editDialogParmas=false
                    this.getCateParamsList()
                })

            },
            //编辑对话框关闭
            editDialogClose(){
                this.$refs.editFormRef.resetFields()
            },
            //删除参数操作
            async delOption(id){
                var result=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                if (result!=='confirm')return this.$message.info('取消了删除操作')
                var {data:res}=await this.$http.delete(`categories/${this.getCateId}/attributes/${id}`)
                if (res.meta.status!==200)return this.$message.error('删除操作失败')
                this.$message.success('删除操作成功')
                this.getCateParamsList()
            },
            //回车和移除焦点时触发
            handleInputConfirm(row){
                //验证是否是全部输入的合法内容
                if (row.inputValue.trim().length===0){
                    row.inputVisible=''
                    row.inputVisible=false
                    return
                }
                //合法内容
                row.attr_vals.push(row.inputValue.trim())
                row.inputValue=''
                row.inputVisible=false

                //发送ajax请求保存
               this.saveTagAjax(row)
            },
            async saveTagAjax(row){
                var {data:res}=await this.$http.put(`categories/${this.getCateId}/attributes/${row.attr_id}`,{
                    attr_name:row.attr_name,
                    attr_sel:row.attr_sel,
                    attr_vals:row.attr_vals.join(' ')
                })
                if (res.meta.status!==200)return this.$message.error('修改数据失败')
                this.$message.success('修改数据成功')
            },
            //单击按钮切换输入框时触发
            showInput(row){
                row.inputVisible=true
                //切换为input之后自动获取焦点
                //$nextTick是等页面被重新渲染之后触发
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            //删除标签
            closeElTag(row,index){
                row.attr_vals.splice(index,1)
                //发送ajax请求保存标签状态
                this.saveTagAjax(row)
            }

        },
        computed:{
            //判断是否需要隐藏按钮
            isDisablle(){
                if (this.modelCascader.length!==3){
                    return true
                }
                return  false
            },
            //获取分类id
            getCateId(){
                if(this.modelCascader.length!==3){
                    return null
                }
                return this.modelCascader[2]
            },
            //动态切换对话框的文字
            dialogText(){
                if(this.activeName=='many'){
                    return '动态参数'
                }
                return '静态属性'
            }
        }
    }
</script>

<style lang="less" scoped>
.el-tag{
    margin: 10px;
}
.input-new-tag{
    width: 100px;
}
</style>